import React, { useEffect, useRef, useState } from 'react'
import Modal from 'antd/es/modal/Modal'
import ProTable from '@ant-design/pro-table'
import { categoryList } from '@/services/category'
import { TestListMod, TestListQuestionData } from '@/services/testList'
import ProFormItem from '@ant-design/pro-form/es/components/FormItem'
import { Button, InputNumber, message, Select, TreeSelect } from 'antd'
import ProForm, {
  ProFormDigit,
  ProFormGroup,
  ProFormSelect,
} from '@ant-design/pro-form'

const Random = (props) => {
  const columns = [
    {
      title: '试题类型',
      dataIndex: 'type',
      align: 'center',
      width: '10%',
      render: (_, record) => [
        <Select
          key={record.key}
          defaultValue={record.type}
          disabled={true}
          bordered={false}
          showArrow={false}
          options={selectOrder}
        />,
      ],
    },
    {
      title: '试题分类',
      className: 'column-money',
      dataIndex: 'category_id',
      align: 'center',
      render: (_, record) => [
        <TreeSelect
          key={record.key}
          bordered={false}
          disabled={true}
          showArrow={false}
          style={{ width: '100%' }}
          allowClear
          value={record.category_id}
          name="category_id"
          treeData={treeData}
        />,
      ],
    },
    {
      title: '不限星',
      width: '12%',
      align: 'center',
      dataIndex: 'levelZero',
    },
    {
      title: '1星',
      align: 'center',
      dataIndex: 'levelOne',
    },
    {
      title: '2星',
      align: 'center',
      dataIndex: 'levelTwo',
    },
    {
      title: '3星',
      align: 'center',
      dataIndex: 'levelThree',
    },
    {
      title: '总题数',
      dataIndex: 'allNum',
      align: 'center',
      width: '6%',
    },
    {
      title: '每题分数',
      dataIndex: 'itemFun',
      align: 'center',
      width: '6%',
    },
    {
      title: '总分数',
      dataIndex: 'allFun',
      align: 'center',
      width: '6%',
    },
    {
      title: '操作',
      align: 'center',
      width: '6%',
      render: (_, record) => [
        <Button type="primary" size="small" key="delete" onClick={async () => {
          setData(data.filter((item) => item.key !== record.key))
          CreateActionRef.current?.reload()
          countUpdate(data.filter((item) => item.key !== record.key))
        }} danger>
          删除
        </Button>,
      ],
    },
  ]
  const columnsTwo = [
    {
      title: '不限星',
      dataIndex: 'levelZero',
      align: 'center',
      width: '16%',
    },
    {
      title: '1星',
      dataIndex: 'levelOne',
      align: 'center',
      width: '16%',
    },
    {
      title: '2星',
      dataIndex: 'levelTwo',
      align: 'center',
      width: '16%',
    },
    {
      title: '3星',
      dataIndex: 'levelThree',
      align: 'center',
      width: '16%',
    },
    {
      title: '数量总计',
      dataIndex: 'allNum',
      align: 'center',
      width: '16%',
    },
    {
      title: '分数总计',
      dataIndex: 'allFun',
      align: 'center',
      width: '16%',
    },
  ]

  const { selectOrder, testListId, setTestListId } = props
  const CreateActionRef = useRef()
  const ContActionRef = useRef()

  let [data, setData] = useState([])
  let [contData, setContData] = useState(null)
  let [selectType, setSelectType] = useState(undefined)
  let [questionNum, setQuestionNum] = useState(undefined)

  const [level, setLevel] = useState({
    'levelZero': 0,
    'levelOne': 0,
    'levelTwo': 0,
    'levelThree': 0,
  })
  const [treeData, setTreeData] = useState(undefined)
  const [questionModal, setQuestionModal] = useState(false)
  const [maxLevelOne, setMaxLevelOne] = useState(undefined)
  const [maxLevelTwo, setMaxLevelTwo] = useState(undefined)
  const [maxLevelZero, setMaxLevelZero] = useState(undefined)
  const [maxLevelThree, setMaxLevelThree] = useState(undefined)

  useEffect(async () => {
    const response = await categoryList({ 'category_group': 'text-bank' })
    if (response !== undefined) {
      const data =
        response.map((item) => {
          return {
            key: item.id,
            value: item.id,
            title: item.name,
            children: item.children ? item.children.map((item) => {
              return {
                key: item.id,
                value: item.id,
                title: item.name,
              }
            }) : [],
          }
        })
      setTreeData(data)
    }
  }, [])

  // 获取分类
  const getTestCategory = () => {
    return (selectOrder)
  }

  /**
   * 获取试题 并显示添加试题modal
   * @param values
   * @returns {Promise<void>}
   */
  const getTestListQuestionData = async (values) => {
    setSelectType(values)
    await TestListQuestionData(values).then((res) => {
      let questionData = {}
      questionData['levelZeroNum'] = res.allNum
      questionData['allNum'] = res.allNum
      res.level.map((item) => {
        if (item.level === 1) {
          questionData['levelOneNum'] = item.sum
        }
        if (item.level === 2) {
          questionData['levelTwoNum'] = item.sum
        }
        if (item.level === 3) {
          questionData['levelThreeNum'] = item.sum
        }
      })
      questionData.levelOneNum !== undefined
        ? questionData.levelOneNum = questionData['levelOneNum']
        : questionData['levelOneNum'] = 0
      questionData.levelTwoNum !== undefined
        ? questionData.levelTwoNum = questionData['levelTwoNum']
        : questionData['levelTwoNum'] = 0
      questionData.levelThreeNum !== undefined
        ? questionData.levelThreeNum = questionData['levelThreeNum']
        : questionData['levelThreeNum'] = 0
      questionData['levelZero'] = 0
      questionData['levelOne'] = 0
      questionData['levelTwo'] = 0
      questionData['levelThree'] = 0
      questionData['selectNum'] = 0
      setMaxLevelZero(questionData.allNum)
      setMaxLevelOne(questionData.levelOneNum)
      setMaxLevelTwo(questionData.levelTwoNum)
      setMaxLevelThree(questionData.levelThreeNum)
      setQuestionNum(questionData)
    })
    setQuestionModal(true)
  }

  /**
   * 关闭添加试题modal
   */
  const clearQuestion = () => {
    setTestListId(undefined)
    setQuestionModal(false)
  }

  /**
   * 修改一条试题数据 并刷新表格
   * @param values
   */
  const createItem = async (values) => {
    let newSelectNum = level.levelZero + level.levelOne + level.levelTwo +
      level.levelThree
    if (newSelectNum > questionNum.allNum) {
      message.error('抽题总数不能大于总数量')
      return
    }

    let oldData = []
    data.map((item) => {
      oldData.push(item)
    })

    let key = data.pop()
    let newData = {}
    newData['key'] = key ? key.key + 1 : 1
    newData['allFun'] = (values.levelZero + values.levelOne + values.levelTwo +
      values.levelThree) * values.itemFun
    newData['levelZero'] = values.levelZero
    newData['levelOne'] = values.levelOne
    newData['levelTwo'] = values.levelTwo
    newData['levelThree'] = values.levelThree
    newData['type'] = selectType.type
    newData['category_id'] = selectType.category_id
    newData['allNum'] = (values.levelZero + values.levelOne + values.levelTwo +
      values.levelThree)
    newData['itemFun'] = values.itemFun

    oldData.push(newData)

    await setData(oldData)

    CreateActionRef.current?.reload()
    countUpdate(oldData)
    setQuestionModal(false)
  }

  /**
   * 更新统计的数量
   */
  const countUpdate = (arr) => {
    let newCountData = [
      {
        key: 1,
        levelZero: 0,
        levelOne: 0,
        levelTwo: 0,
        levelThree: 0,
        allNum: 0,
        allFun: 0,
      },
    ]

    arr.map((item) => {
      newCountData[0]['levelZero'] += item.levelZero
      newCountData[0]['levelOne'] += item.levelOne
      newCountData[0]['levelTwo'] += item.levelTwo
      newCountData[0]['levelThree'] += item.levelThree
      newCountData[0]['allFun'] += item.allFun
      newCountData[0]['allNum'] += item.allNum
    })

    setContData(newCountData)

    ContActionRef.current?.reload()
  }

  /**
   * 获取选择的数量
   */
  const getValue = (value, str) => {
    level[str] = value
  }

  /**
   * 更新数据到服务器
   */
  const submitData = () => {
    let resData = {}
    selectOrder.map((item) => {
      resData[item.value] = {}
    })
    data.map((item, index) => {
      if (item.levelZero !== 0) {
        let arr = {}
        arr['num'] = item.levelZero
        arr['level'] = 0
        arr['fraction'] = item.itemFun
        arr['category_id'] = item.category_id
        resData[item.type][index] = (arr)
      }
      if (item.levelOne !== 0) {
        let arr = {}
        arr['num'] = item.levelOne
        arr['level'] = 1
        arr['fraction'] = item.itemFun
        arr['category_id'] = item.category_id
        resData[item.type][index] = (arr)
      }
      if (item.levelTwo !== 0) {
        let arr = {}
        arr['num'] = item.levelTwo
        arr['level'] = 2
        arr['fraction'] = item.itemFun
        arr['category_id'] = item.category_id
        resData[item.type][index] = (arr)
      }
      if (item.levelThree !== 0) {
        let arr = {}
        arr['num'] = item.levelThree
        arr['level'] = 3
        arr['fraction'] = item.itemFun
        arr['category_id'] = item.category_id
        resData[item.type][index] = (arr)
      }
    })

    let response = ''

    if (testListId !== undefined) {
      response = TestListMod(testListId, { 'random': resData })
    } else {
      message.error('请先创建试卷')
    }

    // 验证是否提交成功
    if (response.status === undefined) {
      message.success('保存成功，您可以继续修改或选择固定题目')
    }
  }

  return (
    <>
      <ProForm submitter={{
        // 配置按钮文本
        searchConfig: {
          resetText: '重置',
          submitText: '下一步',
        },
      }} onFinish={(values) => getTestListQuestionData(values)}>
        <ProFormGroup>
          <ProFormSelect
            name="type"
            width="md"
            label="试题类型"
            request={getTestCategory}
            placeholder="请选择试题类型"
            rules={[{ required: true, message: '您必须选择试题类型!' }]}
          />
          <ProFormItem label="试题分类" name="category_id"
                       rules={[{ required: true, message: '您必须选择试题分类!' }]}>
            <TreeSelect
              style={{ width: '350%' }}
              placeholder="试卷分类"
              allowClear
              treeData={treeData}
            />
          </ProFormItem>
        </ProFormGroup>
      </ProForm>
      <ProTable
        key={1}
        options={false}
        search={false}
        columns={columns}
        request={async () => {
          return {
            data: data,
            success: true,
          }
        }}
        actionRef={CreateActionRef}
        size="small"
        bordered
        pagination={false}
        toolBarRender={() => []}
      />

      <ProTable
        key={2}
        options={false}
        search={false}
        columns={columnsTwo}
        request={async () => {
          return {
            data: contData,
            success: true,
          }
        }}
        actionRef={ContActionRef}
        size="small"
        bordered
        pagination={false}
        toolBarRender={() => []}
      />

      <div style={{ width: '100%', textAlign: 'center', marginTop: 28 }}>
        <Button type="primary" onClick={() => {
          submitData()
        }}>
          保存
        </Button>
      </div>

      <Modal width={'60%'} title="添加试题数据" centered={true} destroyOnClose={true}
             visible={questionModal} footer={false} onCancel={() => {
        clearQuestion()
      }}>
        <ProForm
          submitter={{
            // 配置按钮文本
            searchConfig: {
              resetText: '重置',
              submitText: '提交',
            },
          }}
          initialValues={questionNum}
          onFinish={(values) => {
            createItem(values)
          }}
        >
          <ProFormGroup>
            <ProFormItem label="不限星可选数量" name="levelZeroNum">
              <InputNumber disabled={true}/>
            </ProFormItem>
            <ProFormItem name="levelOneNum" label="1星可选数量">
              <InputNumber disabled={true}/>
            </ProFormItem>
            <ProFormItem name="levelTwoNum" label="2星可选数量">
              <InputNumber disabled={true}/>
            </ProFormItem>
            <ProFormItem name="levelThreeNum" label="3星可选数量">
              <InputNumber disabled={true}/>
            </ProFormItem>
            <ProFormItem name="allNum" label="总数量">
              <InputNumber disabled={true}/>
            </ProFormItem>
          </ProFormGroup>
          <ProFormGroup>
            <ProFormItem label="不限星已选数量" name="levelZero">
              <InputNumber onChange={(value) => getValue(value, 'levelZero')}
                           min={0} max={maxLevelZero}
                           rules={[
                             {
                               required: true,
                               message: '您必须为试题填充数量!',
                             }]}/>
            </ProFormItem>
            <ProFormItem label="1星已选数量" name="levelOne">
              <InputNumber onChange={(value) => getValue(value, 'levelOne')}
                           min={0} max={maxLevelOne}
                           rules={[
                             {
                               required: true,
                               message: '您必须为试题填充数量!',
                             }]}/>
            </ProFormItem>
            <ProFormItem label="2星已选数量" name="levelTwo">
              <InputNumber onChange={(value) => getValue(value, 'levelTwo')}
                           min={0} max={maxLevelTwo}
                           rules={[
                             {
                               required: true,
                               message: '您必须为试题填充数量!',
                             }]}/>
            </ProFormItem>
            <ProFormItem label="3星已选数量" name="levelThree">
              <InputNumber onChange={(value) => getValue(value, 'levelThree')}
                           min={0} max={maxLevelThree}
                           rules={[
                             {
                               required: true,
                               message: '您必须为试题填充数量!',
                             }]}/>
            </ProFormItem>
          </ProFormGroup>
          <ProFormDigit name="itemFun" label="每题分数"/>
        </ProForm>
      </Modal>
    </>
  )
}

export default Random
